﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace AyuBookmark.Service
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var hostBuilder = CreateHostBuilder(args);
            await hostBuilder.Build().RunAsync();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    // 配置基础服务
                    services.AddLogging();
                    services.AddMemoryCache();

                    // 添加后台服务
                    services.AddHostedService<BookmarkBackgroundService>();
                })
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.AddConsole();
                    logging.AddDebug();
                    logging.SetMinimumLevel(LogLevel.Information);
                });
    }

    /// <summary>
    /// 书签后台服务
    /// </summary>
    public class BookmarkBackgroundService : BackgroundService
    {
        private readonly ILogger<BookmarkBackgroundService> _logger;
        private readonly TimeSpan _interval = TimeSpan.FromMinutes(1);

        public BookmarkBackgroundService(ILogger<BookmarkBackgroundService> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("书签服务已启动");

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    // 模拟后台任务
                    _logger.LogInformation("执行书签同步检查...");
                    await Task.Delay(_interval, stoppingToken);
                }
                catch (OperationCanceledException)
                {
                    // 服务停止时正常退出
                    break;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "书签服务发生错误");
                    await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
                }
            }

            _logger.LogInformation("书签服务已停止");
        }
    }
}